package com.xgll.modules.sys.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import com.xgll.common.utils.Query;
import com.xgll.modules.api.entity.GoodsVo;
import com.xgll.modules.api.entity.UserVo;
import com.xgll.modules.api.service.ApiAdService;
import com.xgll.modules.api.service.ApiAttributeService;
import com.xgll.modules.api.service.ApiCategoryService;
import com.xgll.modules.api.service.ApiChannelService;
import com.xgll.modules.api.service.ApiGoodsCrashService;
import com.xgll.modules.api.service.ApiGoodsService;
import com.xgll.modules.api.service.ApiUserService;


@Controller
public class SysPageController {
    @Autowired
    private ApiCategoryService acs;
    @Autowired
    private ApiGoodsService goodsService;
    @Autowired
    private ApiAdService adService;
    @Autowired
    private ApiAttributeService attributeService;
    @Autowired
    private ApiUserService userService;
    @Autowired
    private ApiAttributeService atts;
    @Autowired
    private ApiChannelService channelService;
    @Autowired
    private ApiGoodsCrashService goodsCrashService;

    @RequestMapping("/admin/sys/{url}")
    public String pageAdmin(@PathVariable("url") String url) {
        System.err.println("admin url : " + url);
        return "admin/sys/" + url;
    }

    @RequestMapping("/shop/person/index.html")
    public String pageShopPerson(HttpSession session, Model model) {
        UserVo loginUser = userService.queryObject((long) 15);
        session.setAttribute("loginUser", loginUser);
        model.addAttribute("user", loginUser);
        System.err.println("person url : ");
        return "shop/person/index";
    }

    @RequestMapping("/{url}")
    public String pageShop(@PathVariable("url") String url, Model model) {
        switch (url) {
            case "sort":
            case "search":
            case "index":
            case "introduction":
                Map<String, Object> recommend = adService.recommend();
                List<Map<String, Object>> channel = channelService.channel();
                List<Map<String, Object>> carousel = adService.carousel();
                List<Map<String, Object>> ones = acs.queryByParentId(0);
                for (Map<String, Object> map : ones) {
                    Long id = (Long) map.get("id");
                    List<Map<String, Object>> twos = acs.queryByParentId(id.intValue()), goods = new ArrayList<>(), hd = new ArrayList<>(), bd = new ArrayList<>();
                    /*首页楼层显示商品还应再做优化*/
                    for (Map<String, Object> two : twos) {
                        Long i = (Long) two.get("id");
                        List<Map<String, Object>> good = goodsService.homeGoods(i.intValue());
                        if (goods.size() < 1 && good.size() > 0)
                            goods = good;
                    }
                    for (int i = 0; i < twos.size(); i++) {
                        if (i < 6) {
                            hd.add(twos.get(i));
                        } else {
                            bd.add(twos.get(i));
                        }
                    }
                    map.put("son", twos);
                    map.put("hson", hd);
                    map.put("bson", bd);
                    map.put("goods", goods);
                }
                model.addAttribute("categories", ones);
                model.addAttribute("carousel", carousel);
                model.addAttribute("channel", channel);
                model.addAttribute("recommend", recommend);
                break;
        }
        return url;
    }

    @RequestMapping("/introduction/{id}")
    public String introduction(@PathVariable("id") Integer id, Model model) {
        List<Map<String, Object>> ones = acs.queryByParentId(0);
        for (Map<String, Object> map : ones) {
            Long cid = (Long) map.get("id");
            List<Map<String, Object>> twos = acs.queryByParentId(cid.intValue());
            map.put("son", twos);
        }
        model.addAttribute("categories", ones);
        GoodsVo goodsVo = goodsService.queryObject(id);
        model.addAttribute("goods", goodsVo);
        List<Map<String, Object>> attribute = atts.queryGoodsById(id);
        model.addAttribute("attribute", attribute);

        return "introduction";
    }

    @RequestMapping("/search/")
    public String search(@RequestParam Map<String, Object> map, Model model) {
        String link = (String) map.get("link");
        System.err.println("link : " + link);
        Map<String, Object> linkMap = new HashMap<>(), goodsCrashId = new HashMap<>();
        goodsCrashId.put("goods_ids", goodsCrashService.findGoodsId());
        System.err.println("good crash id : " + goodsCrashId);
        System.err.println("linkMap : " + linkMap);
        for (String value : link.split(";")) {
            String[] v = value.split(":");
            if (v[0].equals("category_id")) {
                Integer id = Integer.parseInt(v[1]);
                linkMap.put(v[0], id);
            } else
                linkMap.put(v[0], v[1]);
        }
        Query query = new Query(linkMap)/*, rashMap = new Query(goodsCrashId)*/;
        Integer category_id = (Integer) query.get("category_id"), pid = Integer.parseInt((String) query.get("pid"));
        List<Map<String, Object>> categories = category(), channel = channelService.channel(), about = acs.queryByParentId(pid), classify = attributeService.classifySearch(category_id);
        List<Integer> family = findChildById(category_id);
        String name = (String) query.get("category_name");
        if (family != null) {
            family.add(category_id);
            query.put("categoryIds", family);
            query.remove("category_id");
        }
        System.err.println("query : " + query);
        /*分页查询*/
        List<GoodsVo> goods = goodsService.queryList(query);
        int count = goodsService.queryCount(query), pages = (int) Math.ceil(count / 36.00), currentPage = (Integer) query.get("page");
        /*若分类不为最终分类，则查询该分类下所有分类的商品*/
        for (Map<String, Object> a : about) {
            Long x = (Long) a.get("id");
            if (x.intValue() == category_id) {
                about.remove(a);
                break;
            }
        }
        for (Map<String, Object> c : classify) {
            if (c.get("value") != "") {
                String value = (String) c.get("value");
                String[] values = value.split(";");
                c.remove("value");
                c.put("value", values);
            }
        }
        List<GoodsVo> goodsCrash = goodsService.queryList(goodsCrashId);
        System.err.println("about : "+about);
        model.addAttribute("name", name);
        model.addAttribute("query", link);
        model.addAttribute("pages", pages);
        model.addAttribute("count", count);
        model.addAttribute("goods", goods);
        model.addAttribute("about", about);
        model.addAttribute("channel", channel);
        model.addAttribute("crash", goodsCrash);
        model.addAttribute("classify", classify);
        model.addAttribute("curPg", currentPage);
        model.addAttribute("categories", categories);
        return "search";
    }

    @RequestMapping("/search&{key}")
    public String keyWord(@RequestParam Map<String, Object> map, @PathVariable("key") String key, Model model) {
        System.err.println("map : " + map);
        Map<String, Object> goodsCrashId = new HashMap<>(), linkMap = new HashMap<>(), pIds = new HashMap<>();
        goodsCrashId.put("goods_ids", goodsCrashService.findGoodsId());
        List<GoodsVo> goodsCrash = goodsService.queryList(goodsCrashId);
        String link = (String) map.get("link");
        for (String value : link.split(";")) {
            String[] v = value.split(":");
            linkMap.put(v[0], v[1]);
        }
        linkMap.put("key", key);
        Query query = new Query(linkMap);
        System.err.println("query : " + query);
        List<Integer> categoriesId = acs.findByKeyWord(key), id = acs.findParentByKey(key);
        List<Map<String, Object>> channel = channelService.channel(), classify = new ArrayList<>(), categories = category(), about = new ArrayList<>();
        if (id.size() > 0) {
            pIds.put("ids", id);
            about = acs.about(pIds);
        }
        System.err.println("pid : " + pIds);
        List<GoodsVo> goods = goodsService.searchByKeyWord(query);
        int count = goodsService.countKeyWord(query), currentPage = (Integer) query.get("page");

        ArrayList<Integer> kFamily = new ArrayList<>();
        if (categoriesId.size() > 0) {
            for (Integer c : categoriesId) {
                List<Integer> kCategory = findChildById(c);
                if (kCategory != null)
                    kFamily.addAll(kCategory);
                classify = attributeService.classifySearch(c);
            }
            kFamily.addAll(categoriesId);
            Map<String, Object> categoryMap = new HashMap<>();
            categoryMap.put("categoryIds", kFamily);
            categoryMap.put("page", Integer.valueOf((String) linkMap.get("page")) - count / 36);
            categoryMap.put("limit", 36 - goods.size());
            Query categoryQuery = new Query(categoryMap);
            count += goodsService.queryCount(categoryQuery);
            if (goods.size() < 36) {
                List<GoodsVo> good = goodsService.queryList(categoryQuery);
                goods.addAll(good);
            }
        }
        model.addAttribute("name", key);
        model.addAttribute("about", about);
        model.addAttribute("query", link);
        model.addAttribute("goods", goods);
        model.addAttribute("count", count);
        model.addAttribute("channel", channel);
        model.addAttribute("crash", goodsCrash);
        model.addAttribute("classify", classify);
        model.addAttribute("curPg", currentPage);
        model.addAttribute("categories", categories);
        model.addAttribute("pages", (int) Math.ceil(count / 36.00));
        return "search";
    }

    private ArrayList<Integer> findChildById(int id) {
        ArrayList<Integer> family = acs.findChildId(id);
        if (family.size() > 0) {
            for (Integer mem : family) {
                ArrayList<Integer> f = findChildById(mem);
                if (f != null)
                    family.addAll(f);
            }
        }
        return family != null && family.size() > 0 ? family : null;
    }

    private List<Map<String, Object>> category() {
        List<Map<String, Object>> categories = acs.queryByParentId(0);
        for (Map<String, Object> category : categories) {
            Long cid = (Long) category.get("id");
            List<Map<String, Object>> son = acs.queryByParentId(cid.intValue());
            category.put("son", son);
        }
        return categories;
    }
}

